package com.learnyou.server.xingzuo.biz.handle;

import com.learnyou.server.xingzuo.biz.handle.annotation.IpFreqLimit;
import com.learnyou.server.xingzuo.dao.repository.service.ISysOperLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author heweifeng
 * @Description:
 * @date 2022/11/23 16:46
 */
@Aspect
@Component
public class IpRequestFrequencyLimitInterceptor {

    @Autowired
    private ISysOperLogService sysOperLogService;

    @Pointcut(value = "@annotation(com.learnyou.server.xingzuo.biz.handle.annotation.IpFreqLimit)")
    public void cutService() {
    }

    @Around("cutService()")
    public Object preHandle(ProceedingJoinPoint point) throws Throwable {
        //获取拦截的方法名
        Signature sig = point.getSignature();
        MethodSignature msig = null;
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        msig = (MethodSignature) sig;
        Object target = point.getTarget();
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());

        //获取操作名称
        IpFreqLimit annotation = currentMethod.getAnnotation(IpFreqLimit.class);
        if (annotation != null) {
            sysOperLogService.log(annotation.code(), annotation.title());
            sysOperLogService.checkReqFrequency(annotation.code(), annotation.timeLimit(), annotation.timeUnit(), annotation.maxReqCount());

        }
        return point.proceed();
    }
}
